package com.kcht.np.common.component;

import com.kcht.np.common.domain.SimpleFile;
import org.apache.commons.io.IOUtils;
import org.springframework.http.*;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

public class SimpleFileHttpMessageConverter extends AbstractHttpMessageConverter<SimpleFile> {

    public SimpleFileHttpMessageConverter() {
        super(MediaType.APPLICATION_OCTET_STREAM);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return SimpleFile.class.isAssignableFrom(clazz);
    }

    @Override
    protected SimpleFile readInternal(Class<? extends SimpleFile> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        HttpHeaders headers = inputMessage.getHeaders();
        byte[] bytes = IOUtils.readFully(inputMessage.getBody(), (int) headers.getContentLength());
        return SimpleFile.get(bytes,headers.getContentDisposition().getFilename());
    }

    @Override
    protected void writeInternal(SimpleFile simpleFile, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        OutputStream out= outputMessage.getBody();
        out.write(simpleFile.getBytes());
    }

    @Override
    protected void addDefaultHeaders(HttpHeaders headers, SimpleFile simpleFile, MediaType contentType) throws IOException {
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.parse("attachment; filename=" + simpleFile.getFileName()));
        headers.setContentLength(simpleFile.getBytes().length);
        headers.setAccessControlExposeHeaders(new ArrayList<String>(){{add(HttpHeaders.CONTENT_TYPE);
                add(HttpHeaders.CONTENT_DISPOSITION);
                add(HttpHeaders.CONTENT_LENGTH);
        }});
    }
}
